package com.ebookstore.service.impl;

import java.util.List;

import org.apache.catalina.Session;

import com.ebookstore.dao.BaseDAO;
import com.ebookstore.dto.UserInfo;
import com.ebookstore.exception.EBookStoreException;
import com.ebookstore.service.UserService;

public class UserServiceImpl implements UserService {
	
	// 数据库访问对象
	private BaseDAO userDao = new BaseDAO();
	//定义的常量
	private static final String EXISTED = "Existed";
	private static final String SUCCESS = "Success";

	public UserServiceImpl() {
		super();
	}

	/**
	 * <p>
	 * 方法实现的功能 : 通过用户名和密码判断用户是否已注册
	 * </p>
	 * @param username
	 * @param pwd
	 * @return
	 * @see com.ebookstore.service.UserService#findUserByNameandPwd(java.lang.String,
	 *      java.lang.String)
	 */
	public List findUserByNameandPwd(String username, String pwd) {
//		System.out.println("userservice.findUserByNameandPwd():"+((UserInfo)userDao.findByHql(
//				"from UserInfo where userName='"+username
//				+"' and password='"+pwd+"'").get(0)).getUserId());
		return userDao.findByHql("from UserInfo where userName='"+username
				+"' and password='"+pwd+"'");
	}

	/**
	 * <p>
	 * 方法实现的功能 : 通过Id找到UserInfo
	 * </p>
	 * 
	 * @param userId
	 * @return
	 */
	public UserInfo findUserById(Integer userId) {
		System.out.println("user service.finduserbyID()");
		return (UserInfo) userDao.findById(userId, UserInfo.class);
	}

	/**
	 * <p>
	 * 方法实现的功能 : 添加一个注册用户
	 * </p>
	 * 
	 * @param user
	 */
	public String addUser(UserInfo user) {
		try {
			System.out.println("userservice.adduser()");
			List list = findUserByNameandPwd(user.getUserName(), user
					.getPassword());
			if (!list.isEmpty())
				return EXISTED;
			
			userDao.addObject(user);
		} catch (EBookStoreException e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

	/**
	 * <p>
	 * 方法实现的功能 : 删除一个注册用户
	 * </p>
	 * 
	 * @param user
	 */
	public void removeUser(UserInfo user) {
		try {
			userDao.deleteObject(user);
		} catch (EBookStoreException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <p>
	 * 方法实现的功能 : 修改注册用户的信息
	 * </p>
	 * 
	 * @param user
	 */
	public void updateUser(UserInfo user) {
		try {
			userDao.updateObject(user);
		} catch (EBookStoreException e) {
			e.printStackTrace();
		}
	}

}
